from common.utils.rights import permission_required, view_logging_required
from common.utils.file_read import file_read
from . import index_bp
from flask import render_template,request
from flask_wtf.form import CombinedMultiDict
from models.form import UploadForm
import cv2 as cv
import numpy as np


def sobel(img):
    # sobel算子锐化
    # 对x方向梯度进行sobel边缘提取
    x=cv.Sobel(img,cv.CV_64F,1,0)
    # 对y方向梯度进行sobel边缘提取
    y=cv.Sobel(img,cv.CV_64F,0,1)
    # 对x方向转回uint8
    absX=cv.convertScaleAbs(x)
    # 对y方向转会uint8
    absY=cv.convertScaleAbs(y)
    # x，y方向合成边缘检测结果
    dst1=cv.addWeighted(absX,0.5,absY,0.5,0)
    # 与原图像堆叠
    res=dst1+img
    return res


def lapras(img):
    kernel=np.array([[0,-1,0],[-1,5,-1],[0,-1,0]],np.float32)#定义拉普拉斯算子
    res=cv.filter2D(img,-1,kernel=kernel)#调用opencv图像锐化函数
    return res


@index_bp.get('/sharpen_pro')
@index_bp.post('/sharpen_pro')
@view_logging_required
@permission_required("sharpen:pro")
def sharpen_pro():
    if request.method == "GET":
        return render_template('admin/cv/sharpen.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            f = request.files['file']
            file_url = file_read(f)
            pic = cv.imread(file_url)
            choose = int(request.form.get('choose'))
            res_pic = "static/download/sharpen.jpg"
            if choose == 0:
                out_image = sobel(pic)
                cv.imwrite(res_pic, out_image)
            elif choose == 1:
                out_image = lapras(pic)
                cv.imwrite(res_pic, out_image)
            return render_template('admin/cv/sharpen.html', pic=file_url, res_pic=res_pic)
        else:
            return "请传入正确的文件格式"